from utils import debug_info


class WifiHandler:
	AP_MODE = 0
	STA_MODE = 1

	def __init__(self):
		pass

	@staticmethod
	def set_ap_status(active: bool):
		import network

		access_point = network.WLAN(network.AP_IF)
		access_point.active(active)

	@staticmethod
	def set_sta_status(active: bool):
		import network

		station = network.WLAN(network.STA_IF)
		station.active(active)

	@staticmethod
	def set_sta_mode(essid, password):
		import network
		from utime import sleep_ms

		status_message = {
			network.STAT_IDLE: "network idle",
			network.STAT_CONNECT_FAIL: "network connect failed",
			network.STAT_CONNECTING: "",
			network.STAT_GOT_IP: "Connected",
			network.STAT_NO_AP_FOUND: "could not found ap",
			network.STAT_WRONG_PASSWORD: "wrong password given"
		}

		station = network.WLAN(network.STA_IF)

		station.active(False)
		station.active(True)

		debug_info("\nConnecting to network...")

		station.connect(essid, password)

		while not station.isconnected():
			result_code = station.status()

			if result_code == network.STAT_IDLE or\
				result_code == network.STAT_CONNECT_FAIL or\
				result_code == network.STAT_GOT_IP or\
				result_code == network.STAT_NO_AP_FOUND or\
				result_code == network.STAT_WRONG_PASSWORD:
				break
			elif result_code == network.STAT_CONNECTING:
				pass

			sleep_ms(500)

		status_code = station.status()

		debug_info(status_message[status_code])
		debug_info(station.ifconfig())

		return status_code

	@staticmethod
	def get_mac_address(mode):
		"""
		get AP/STA mode mac address
		:param mode: AP or STA
		:return: mac address
		"""

		import network

		if mode == WifiHandler.AP_MODE:
			adapter = network.WLAN(network.AP_IF)
		elif mode == WifiHandler.STA_MODE:
			adapter = network.WLAN(network.STA_IF)
		else:
			return -1

		mac = adapter.config("mac")

		return ("%02x%02x%02x%02x%02x%02x" % (mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])).upper()
